package com.lcj.OwnerMyBatis.config;

import com.lcj.OwnerMyBatis.pojo.Configuration;
import com.lcj.OwnerMyBatis.pojo.MappedStatement;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @Author：liuchangjun
 * @Date：2021/10/27
 */
@AllArgsConstructor
@NoArgsConstructor
public class XMLMapperBuilder {

    private Configuration configuration;

    public void parse(InputStream inputStream) throws DocumentException {
        Document document =  new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();
        List<Element> elementList = rootElement.selectNodes("//select");
        String nameSpace = rootElement.attributeValue("namespace");
        for(Element element : elementList){
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement(id,resultType,paramterType,sql);
            configuration.getMappedStatementMap().put(nameSpace+"."+id,mappedStatement);
        }
    }
}
